package com.tools.scanner.network

import android.util.Base64
import com.tools.scanner.utils.AppUtil
import com.tools.scanner.utils.NativeUtil
import okhttp3.Interceptor
import okhttp3.Response
import java.util.Locale
import java.util.UUID

class ParamsInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val nonce = UUID.randomUUID().toString()
        val timestamp = (System.currentTimeMillis() / 1000).toString()
        val sign = Base64.encode(NativeUtil.encrypt(nonce, timestamp), Base64.NO_WRAP)

        val oldRequest = chain.request()

        val newRequestBuilder = oldRequest.newBuilder()
        newRequestBuilder.addHeader("x-nonce", nonce)
        newRequestBuilder.addHeader("x-timestamp", timestamp)
        newRequestBuilder.addHeader("x-sign", String(sign))
        newRequestBuilder.addHeader("packageName", AppUtil.getPackageName())
        newRequestBuilder.addHeader(
            "country",
            AppUtil.getOSCountry().uppercase(Locale.getDefault())
        )
        newRequestBuilder.addHeader("language", AppUtil.getOSLang().uppercase(Locale.getDefault()))
        val newRequest = newRequestBuilder.build()
        return chain.proceed(newRequest)
    }
}
